package com.seeyon.apps.kk.manager;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.collaboration.api.CollaborationApi;
import com.seeyon.apps.collaboration.event.CollaborationAddCommentEvent;
import com.seeyon.apps.collaboration.event.CollaborationAppointStepBackEvent;
import com.seeyon.apps.collaboration.event.CollaborationCancelEvent;
import com.seeyon.apps.collaboration.event.CollaborationFinishEvent;
import com.seeyon.apps.collaboration.event.CollaborationProcessEvent;
import com.seeyon.apps.collaboration.event.CollaborationStartEvent;
import com.seeyon.apps.collaboration.event.CollaborationStepBackEvent;
import com.seeyon.apps.collaboration.event.CollaborationStopEvent;
import com.seeyon.apps.collaboration.event.CollaborationTakeBackEvent;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.edoc.bo.EdocSummaryBO;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.dao.SyncOrgDao;
import com.seeyon.apps.kk.util.CollaborationEventThread;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.affair.util.AffairUtil;
import com.seeyon.ctp.common.affair.util.WFComponentUtil;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.constants.ApplicationSubCategoryEnum;
import com.seeyon.ctp.common.content.affair.constants.StateEnum;
import com.seeyon.ctp.common.content.affair.constants.SubStateEnum;
import com.seeyon.ctp.common.content.comment.CommentManager;
import com.seeyon.ctp.common.ctpenumnew.EnumNameEnum;
import com.seeyon.ctp.common.detaillog.vo.FlowNodeDetailAffairVO;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.i18n.ResourceUtil;
import com.seeyon.ctp.common.permission.manager.PermissionManager;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.comment.CtpCommentAll;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.ListenEvent;
import com.seeyon.ctp.workflow.wapi.WorkflowApiManager;
import com.seeyon.v3x.common.taglibs.functions.Functions;
import com.seeyon.v3x.worktimeset.exception.WorkTimeSetExecption;
import com.seeyon.v3x.worktimeset.manager.WorkTimeManager;

public class CollaborationEventLog {
	
	private static final Log log = LogFactory.getLog(CollaborationEventLog.class);
    private SyncOrgDao baseQiangsDao;
	private OrgManager orgManager;
	private WorkflowApiManager	wapi;
	private FormApi4Cap4 formApi4Cap4;
	private AffairManager affairManager;
	private WorkTimeManager workTimeManager;
	private CommentManager ctpCommentManager;
	private CollaborationApi collaborationApi;
	private PermissionManager permissionManager;
	
	private static int year;
	private static Integer workTime = 0;
	
	//发起
	@ListenEvent(event = CollaborationStartEvent.class)
	public void onCollaborationStartEvent(CollaborationStartEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = event.getAffair();
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			commonCtpAffairVO(nodeDetail);
			
			new CollaborationEventThread(formName, affair, nodeDetail);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("发起************"+JSONUtil.toJSONString(event));
	}
	
	//处理
	@ListenEvent(event = CollaborationProcessEvent.class)
	public void onCollaborationProcessEvent(CollaborationProcessEvent event){
		//System.out.println("处理************"+JSONUtil.toJSONString(event));
	}

	//结束
	@ListenEvent(event = CollaborationFinishEvent.class)
	public void CollaborationFinishEvent(CollaborationFinishEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = event.getAffair();
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			affair.setReceiveTime(summary.getCreateDate());
			affair.setCreateDate(summary.getCreateDate());
			commonCtpAffairVO(nodeDetail);
			nodeDetail.setStateLabel("结束");
			
			CtpCommentAll comment = null;
			List<CtpCommentAll> commentList = ctpCommentManager.findCommentsByAffairId(affair.getId());
			if(CollectionUtils.isNotEmpty(commentList)){
				comment = commentList.get(0);
//				comment.setContent("");
			} else {
				log.error("##强生客开异常------流程结束************");
				return ;
			}
			new CollaborationEventThread(formName, comment, nodeDetail);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("结束************"+JSONUtil.toJSONString(event));
	}

	//撤销
	@ListenEvent(event = CollaborationCancelEvent.class)
	public void onCollaborationCancelEvent(CollaborationCancelEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = null;
			List<CtpAffair> list = affairManager.getAffairs(summary.getId());
			for(CtpAffair ctpAffair : list){
				if("newCol".equals(ctpAffair.getNodePolicy())){
					affair = ctpAffair;
					break;
				}
			}	
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			commonCtpAffairVO(nodeDetail);
			
			CtpCommentAll comment = null;
			List<CtpCommentAll> commentList = ctpCommentManager.findCommentsByAffairId(affair.getId());
			if(CollectionUtils.isNotEmpty(commentList)){
				comment = commentList.get(0);
			} else {
				log.error("##强生客开异常------流程撤销************");
				return ;
			}
			new CollaborationEventThread(formName, comment, nodeDetail);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("撤销************"+JSONUtil.toJSONString(event));
	}

	//回退
	@ListenEvent(event = CollaborationStepBackEvent.class)
	public void onCollaborationStepBackEvent(CollaborationStepBackEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = event.getAffair();
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			commonCtpAffairVO(nodeDetail);
			
			CtpCommentAll comment = null;
			List<CtpCommentAll> commentList = ctpCommentManager.findCommentsByAffairId(affair.getId());
			if(CollectionUtils.isNotEmpty(commentList)){
				comment = commentList.get(0);
			} else {
				log.error("##强生客开异常------流程回退************");
				return ;
			}
			new CollaborationEventThread(formName, comment, nodeDetail);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("回退************"+JSONUtil.toJSONString(event));
	}
	
	@ListenEvent(event = CollaborationAppointStepBackEvent.class)
	public void onCollaborationAppointStepBackEvent(CollaborationAppointStepBackEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = null;
			while(affair == null){
				affair = baseQiangsDao.getAffair(event.getSummaryId(), AppContext.currentUserId());//-6795083427597693203
				try {
					if(affair == null){
						Thread.sleep(500L);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
			}
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			commonCtpAffairVO(nodeDetail);
			
			CtpCommentAll comment = null;
			List<CtpCommentAll> commentList = ctpCommentManager.findCommentsByAffairId(affair.getId());
			if(CollectionUtils.isNotEmpty(commentList)) {
				comment = commentList.get(0);
			} else {
				log.error("##强生客开异常------指定回退************");
				return ;
			}
			new CollaborationEventThread(formName, comment, nodeDetail);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
	}

	//终止
	@ListenEvent(event = CollaborationStopEvent.class)
	public void onCollaborationStepBackEvent(CollaborationStopEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = event.getAffair();
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			commonCtpAffairVO(nodeDetail);
			
			CtpCommentAll comment = null;
			List<CtpCommentAll> commentList = ctpCommentManager.findCommentsByAffairId(affair.getId());
			if(CollectionUtils.isNotEmpty(commentList)){
				comment = commentList.get(0);
			} else {
				log.error("##强生客开异常------流程终止************");
				return ;
			}
			new CollaborationEventThread(formName, comment, nodeDetail);
			
			/**********dd流程状态回写DDDistributorTotalState**********/
			Long formId = summary.getFormAppid();
			FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.ddApplyCode);
            FormBean renewBean = formApi4Cap4.getFormByFormCode(Constants.ddRenew);
            if(formBean.getId().equals(formId)
            		|| renewBean.getId().equals(formId)){
            	try {
            		FormDataMasterBean dataMaster = formApi4Cap4.findDataById(summary.getFormRecordid(), formId, null);
            		String flowNo = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay("经销商ID").getName()).toString();
                	
            		FormBean stateBean = formApi4Cap4.getFormByFormCode(Constants.DDDState);
                	FlipInfo fli = new FlipInfo(1, 20);
                    Map<String, Object> where = new HashMap<String, Object>();
                    where.put(stateBean.getFieldBeanByDisplay("Id").getName(), flowNo);//经销商ID
                    List<FormDataMasterBean> list = formApi4Cap4.findMasterDataList(fli, stateBean.getId(), null, where);
                    if(CollectionUtils.isNotEmpty(list)){
                    	FormDataMasterBean stateFormDataMaster =list.get(0);
                    	stateFormDataMaster.addFieldValue(stateBean.getFieldBeanByDisplay("FlowState").getName(), "S018");
                    	stateFormDataMaster.addFieldValue(stateBean.getFieldBeanByDisplay("CreateDate").getName(), DateUtil.currentDate());
                    	stateFormDataMaster.addFieldValue(stateBean.getFieldBeanByDisplay("CreateBy").getName(), AppContext.currentUserId());
                    	formApi4Cap4.saveOrUpdateFormData(stateFormDataMaster, stateBean.getId(), true);
                    }
				} catch (Exception e) {
					// TODO Auto-generated catch block
					log.error("##强生客开异常", e);
				}
            }
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("终止************"+JSONUtil.toJSONString(event));
	}

	//取回
	@ListenEvent(event = CollaborationTakeBackEvent.class)
	public void onCollaborationTakeBackEvent(CollaborationTakeBackEvent event){
		try {
			ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
			String formName = formApi4Cap4.getForm(summary.getFormAppid()).getFormName();
			CtpAffair affair = event.getAffair();
			FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
			commonCtpAffairVO(nodeDetail);
			
			new CollaborationEventThread(formName, affair, nodeDetail);
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("取回************"+JSONUtil.toJSONString(event));
	}

	//处理回复
	@ListenEvent(event = CollaborationAddCommentEvent.class)
	public void onCollaborationAddComment(CollaborationAddCommentEvent event){
		try {
			
			CtpCommentAll comment = ctpCommentManager.getById(event.getCommentId());
			if(comment.getPid().intValue() == 0) {
				CtpAffair affair = affairManager.get(comment.getAffairId());
				String formName = formApi4Cap4.getForm(affair.getFormAppId()).getFormName();
				FlowNodeDetailAffairVO nodeDetail = ctpAffair2ctpAffairVO(affair);
				commonCtpAffairVO(nodeDetail);
				
				new CollaborationEventThread(formName, comment, nodeDetail);
			}
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开异常", e);
		}
//		System.out.println("处理回复************"+JSONUtil.toJSONString(event));
	}
	
	private FlowNodeDetailAffairVO ctpAffair2ctpAffairVO(CtpAffair affair) {
        
    	if (affair == null) {
            return null;
        }
        FlowNodeDetailAffairVO vo = new FlowNodeDetailAffairVO();
        vo.setActivityId(affair.getActivityId());
        vo.setAddition(affair.getAddition());
        vo.setApp(affair.getApp());
        vo.setSubApp(affair.getSubApp());
        vo.setArchiveId(affair.getArchiveId());
        vo.setBodyType(affair.getBodyType());
        vo.setCompleteTime(affair.getCompleteTime());
        vo.setCreateDate(affair.getCreateDate());
        vo.setFirstViewDate(affair.getFirstViewDate());
        vo.setDeadlineDate(affair.getDeadlineDate());
        //处理期限
        if(affair.getExpectedProcessTime()!=null){
        	vo.setDeadline(WFComponentUtil.getDeadLineName(affair.getExpectedProcessTime()));
        }else{
        	 vo.setDeadline(WFComponentUtil.getDeadLineName(affair.getDeadlineDate()));
        }
        vo.setDealTermType(affair.getDealTermType());
        vo.setDealTermUserid(affair.getDealTermUserid());
        vo.setDelete(affair.isDelete());
        vo.setDueRemind(affair.isDueRemind());
        vo.setExtProps(affair.getExtProps());
        vo.setFinish(affair.isFinish());
        vo.setFormAppId(affair.getFormAppId());
        vo.setForwardMember(affair.getForwardMember());
        vo.setFromId(affair.getFromId());
        vo.setHastenTimes(affair.getHastenTimes());
        vo.setIdentifier(affair.getIdentifier());
        vo.setImportantLevel(affair.getImportantLevel());
        vo.setMemberId(affair.getMemberId());
        vo.setNodePolicy(affair.getNodePolicy());
        vo.setObjectId(affair.getObjectId());
        vo.setOverTime(affair.getOverTime());
        vo.setOverWorktime(affair.getOverWorktime());
        vo.setReceiveTime(affair.getReceiveTime());
        vo.setRemindDate(affair.getRemindDate());
        vo.setRemindInterval(affair.getRemindInterval());
        vo.setResentTime(affair.getResentTime());
        vo.setRunWorktime(affair.getRunWorktime());
        vo.setSenderId(affair.getSenderId());
        vo.setState(affair.getState());
        vo.setSubApp(affair.getSubApp());
        vo.setSubject(WFComponentUtil.mergeSubjectWithForwardMembers(affair.getSubject(),-1,affair.getForwardMember(),affair.getResentTime(),null));
        vo.setSubObjectId(affair.getSubObjectId());
        vo.setSubState(affair.getSubState());
        String subStateName = ResourceUtil.getString("collaboration.substate."+affair.getSubState()+".label");
        vo.setSubStateName(subStateName);
        vo.setTempleteId(affair.getTempleteId());
        vo.setTrack(affair.getTrack());
        vo.setTransactorId(affair.getTransactorId());
        //UpdateDate将作为置顶辅助参数使用,所以置顶之后这个参数值不准,尽量不要使用
        //vo.setUpdateDate(affair.getUpdateDate());
        vo.setCoverTime(affair.isCoverTime());
        vo.setEntityId(affair.getId());
        
        vo.setProcessId(Strings.isBlank(affair.getProcessId()) ? 0l : Long.valueOf(affair.getProcessId()));
        //发起人(处理人)
        vo.setHandler(Functions.showMemberName(affair.getSenderId()));
        //类型
        vo.setAppName(ResourceUtil.getString("application."+affair.getApp()+".label"));
        vo.setHasAttsFlag(AffairUtil.isHasAttachments(affair));
        return vo;
    }
	
	/**
     * 对List<CtpAffairVO> affairVOList 进行特殊处理
     * @param affairVOList
     * @return
     * @throws BusinessException
     */
    private FlowNodeDetailAffairVO commonCtpAffairVO(FlowNodeDetailAffairVO affairVO) throws BusinessException {

        if (affairVO != null) {
            Long _accountId = AppContext.getCurrentUser().getLoginAccount();
            Long orgAccountId = 0l;
            Map<String ,String> nodeIdToNameMap = null;
            String handler = "";
            String policyName = "";
            Date createDate = null;
            Date finishDate = null;
            String dealTime = null;
            String stateLabel = "";
            String deadline = null;
            //如果affair为公文收发员处理的已封发的公文事项（即待发送公文和已发送公文），不显示在处理明细节点中。
            //因为此时的affair不在流程中，获取节点权限异常
            if (affairVO.getApp() == ApplicationCategoryEnum.exSend.getKey())
                return null; //待发送22
            if (affairVO.getApp() == ApplicationCategoryEnum.exSign.getKey())
            	return null; //待签收23
            if (affairVO.getApp() == ApplicationCategoryEnum.edocRegister.getKey())
            	return null; //待登记24
            String appName = "";
            String processId = "";
            Date _finishDate = null;
            //已发列表
            if (Integer.valueOf(StateEnum.col_sent.key()).equals(affairVO.getState()) 
            		|| Integer.valueOf(StateEnum.col_waitSend.key()).equals(affairVO.getState())) {
                Long senderId = affairVO.getSenderId();
                V3xOrgMember member = orgManager.getMemberById(senderId);
                if (member != null) {
                    handler = member.getName();
                    if (!_accountId.equals(member.getOrgAccountId())) { //同一个单位的
                        String accountShortname = orgManager.getAccountById(member.getOrgAccountId())
                                .getShortName();
                        handler += "(" + accountShortname + ")";
                    }
                }
                createDate = affairVO.getCreateDate();
                //客开 项目名称： [修改功能：] 作者：fzc 修改日期：2018-4-28 start
                boolean isNewSend  = affairVO.getApp() == ApplicationCategoryEnum.edoc.getKey() && (affairVO.getSubApp().intValue() == ApplicationSubCategoryEnum.edoc_fawen.getKey() || affairVO.getSubApp().intValue() == ApplicationSubCategoryEnum.edoc_qianbao.getKey());
                if (affairVO.getApp().intValue() == ApplicationCategoryEnum.edocSend.getKey()
                        || affairVO.getApp() == ApplicationCategoryEnum.edocSign.getKey() || isNewSend) {
                    //发文,签报
                    policyName = ResourceUtil.getString("node.policy.niwen");
                }
                boolean isNewRec = affairVO.getApp() == ApplicationCategoryEnum.edoc.getKey() && affairVO.getSubApp().intValue() == ApplicationSubCategoryEnum.edoc_shouwen.getKey();
                if (affairVO.getApp().intValue() == ApplicationCategoryEnum.edocRec.getKey() || isNewRec) {
                    //客开 项目名称： [修改功能：] 作者：fzc 修改日期：2018-4-28 end
                    //收文
                    policyName = ResourceUtil.getString("node.policy.dengji" + Functions.suffix());
                }
                boolean isExchange = affairVO.getApp() == ApplicationCategoryEnum.edoc.getKey() && affairVO.getSubApp().intValue() == ApplicationSubCategoryEnum.edoc_jiaohuan.getKey();
                if (affairVO.getApp().intValue() == ApplicationCategoryEnum.edocRec.getKey() || isExchange) {
                    policyName = ResourceUtil.getString("node.policy.niwen");
                }
                if (affairVO.getApp().intValue() == ApplicationCategoryEnum.collaboration.getKey()) {
                	if("newCol".equals(affairVO.getNodePolicy())){
                		policyName = ResourceUtil.getString("node.policy.newCol");
                	}else{
                		policyName = ResourceUtil.getString("node.policy.collaboration");
                	}
                }

                if(affairVO.getApp().intValue() == ApplicationCategoryEnum.info.getKey()){
                    policyName = ResourceUtil.getString("node.policy.shangbao");
                }

            } else {
                Long memberId = affairVO.getMemberId();
                V3xOrgMember member = orgManager.getMemberById(memberId);
                if (member != null) {
                    handler = member.getName();
                    if (!_accountId.equals(member.getOrgAccountId())) { //同一个单位的
                        String accountShortname = orgManager.getAccountById(member.getOrgAccountId())
                                .getShortName();
                        handler += "(" + accountShortname + ")";
                    }
                }
                else{
                    if(nodeIdToNameMap == null){
                        nodeIdToNameMap = wapi.getRunningProcessNodeIdAndName(affairVO.getProcessId());
                    }
                    handler = nodeIdToNameMap.get(String.valueOf(affairVO.getActivityId()));
                }
                Long summaryId = affairVO.getObjectId();
                ColSummary summary = null;
                EdocSummaryBO eSummary = null;
                //TODO DEV 2015-08-19 InfoSummary 还未迁移
                //InfoSummary infoSummary = null;
                //协同
                summary = collaborationApi.getColSummary(summaryId);
                orgAccountId = collaborationApi.getFlowPermAccountId(summary.getOrgAccountId(), summary);
                appName = ApplicationCategoryEnum.collaboration.name();
                policyName = permissionManager.getPermissionName(EnumNameEnum.col_flow_perm_policy.name(), affairVO.getNodePolicy(), orgAccountId);
                if (summary.getProcessId() != null) {
                	processId = summary.getProcessId().toString();
				}

                if (Strings.isBlank(policyName)) {
                    String[] policy = wapi.getNodePolicyIdAndName(appName,processId, affairVO.getActivityId() == null ? "start" : affairVO
                                    .getActivityId().toString());
                    if (policy != null && policy.length > 1) {
                        policyName = policy[1];
                    }
                }
                createDate = affairVO.getReceiveTime();
                finishDate = affairVO.getCompleteTime();
//                    Date updateDate = affairvo.getUpdateDate();
                Date _createDate = null;
                if (createDate != null) {
                    _createDate = new Date(createDate.getTime());
                }

                //如果没有完成(处理)时间,取更新时间
                if (finishDate != null) {
                    _finishDate = new Date(finishDate.getTime());
                }else  if (affairVO.getState() == StateEnum.col_pending.key() && affairVO.getSubState() == SubStateEnum.col_pending_ZCDB.key()) {
                    _finishDate = affairVO.getUpdateDate();
                }
                //计算处理时长
                if (_createDate != null && _finishDate != null) {
                    Long intervalTime = Functions.getMinutesBetweenDatesByWorkTime(_createDate, _finishDate, orgAccountId);
                    if(intervalTime != null){
                    	dealTime = Functions.showDateByWork(Integer.parseInt(intervalTime.toString()));
                    }
                }
                //处理期限(节点期限)
//                    if (affair.getDeadlineDate() != null && affair.getDeadlineDate() != 0) {
//                        long[] deadlineArr = Datetimes.formatLongToTimeStr(affair.getDeadlineDate() * 60000);
//                        long date1 = deadlineArr[0];
//                        long hour1 = deadlineArr[1];
//                        long minut1 = deadlineArr[2];
//                        deadline = ColUtil.timePatchwork(date1, hour1, minut1, 0L, true);
//                    }
                	deadline = affairVO.getDeadline();
            }
            int state = affairVO.getState();
            Integer subState = affairVO.getSubState();
            if (subState == null) {
                subState = SubStateEnum.col_normal.key();
            }
            if (state == StateEnum.col_pending.key() && subState == SubStateEnum.col_pending_ZCDB.key()) {
                stateLabel = ResourceUtil.getString("collaboration.substate.13.label");
                //暂存待办 时 不计算处理时长,将其值为null
                dealTime = null;
            } else if (state == StateEnum.col_sent.key()) {
                stateLabel = ResourceUtil.getString("collaboration.state.12.col_sent");
            } else if ((state == StateEnum.col_pending.key()&& subState != SubStateEnum.col_pending_ZCDB.key())
            			|| state == StateEnum.col_pending_repeat_auto_deal.key()) {
                stateLabel = ResourceUtil.getString("collaboration.state.13.col_pending");
            } else if (state == StateEnum.col_done.key()) {
                stateLabel = ResourceUtil.getString("collaboration.state.14.done");
                if (subState == SubStateEnum.col_done_stepStop.key()) {
                    stateLabel += "(" + ResourceUtil.getString("collaboration.state.10.stepstop") + ")";
                }
            } else if (state == StateEnum.col_waitSend.key()) {
                stateLabel = ResourceUtil.getString("collaboration.state.11.waitSend");
            }
            //发起、收到时间（如果是已发、待发 则是 创建时间、其它的为收到时间）
            affairVO.setCreateDate(createDate);
            //处理时长
            affairVO.setDealTime(dealTime);
            //处理期限
            affairVO.setDeadline(deadline);
            //处理时间
            affairVO.setFinishDate(_finishDate);
            //处理人
            affairVO.setHandler(handler);
            //节点权限
            affairVO.setPolicyName(policyName);
            //处理状态
            affairVO.setStateLabel(stateLabel);
            //没有超期时长动态运行.
            affairVO.setDeadlineTime(affairVO.getOverWorktime()==null?null:showDate(Integer.parseInt(affairVO.getOverWorktime().toString()),true));
            boolean isCompute = false;
            Date computeEndDate = new Date();
            //设置了节点期限的才需要计算.  计算超长时长
//                if (affairvo.getDeadlineDate() != null && affairvo.getDeadlineDate() != 0) {
            if (affairVO.getDeadline() != null) {    // 根据传入的节点期限时间来判断
                if (affairVO.getState().intValue() == StateEnum.col_done.key() && affairVO.getOverWorktime() == null) {
                    isCompute = true;
                    computeEndDate = affairVO.getCompleteTime();
                } else if (affairVO.getState().intValue() == StateEnum.col_pending.key()) {
                    isCompute = true;
                }
            }
            if (isCompute) {
                try {
                    long time = workTimeManager.getDealWithTimeValue(affairVO.getReceiveTime(), computeEndDate,orgAccountId);
                    time = time / (60 * 1000); //毫秒转化为分钟
                    long workDeadLine = 0l;
                    long over = 0l;
                    if (affairVO.getDeadlineDate() != null && affairVO.getDeadlineDate() != 0) {
                        workDeadLine = workTimeManager.convert2WorkTime(Long.parseLong(affairVO.getDeadlineDate().toString()), orgAccountId);
                        over = time - workDeadLine;
                        affairVO.setOverWorktime(over > 0 ? over : 0);
                        if(over > 0){
                        	affairVO.setCoverTime(true);
                        }
                    }

                    affairVO.setDeadlineTime(showDate(Integer.parseInt(over+""),true));


                } catch (Exception e) {
				}
            }
            
            if((affairVO.getDeadline() == null || "".equals(affairVO.getDeadline()))){
            	affairVO.setOverWorktime(0l);
            	affairVO.setDeadlineTime(null);
            }
        }
        return affairVO;
    }
    
    /**
     * 将分钟数按当前工作时间转化为按天表示的时间。
     * 例如 1天7小时2分。
     */
    private  String showDate(Integer minutes,boolean isWork){
        if(minutes == null || minutes == 0)
            return "－";
        int dayH = 24*60;
        if(isWork){
            Calendar cal = Calendar.getInstance();
            int y = cal.get(Calendar.YEAR);
            if(year != y || workTime.intValue() == 0 ){ //需要取工作时间
                workTime = getCurrentYearWorkTime();
                year = y;
            }
            if(workTime == null || workTime.intValue() == 0){
            	return "－";
            }
            dayH = workTime;
        }

        long m = minutes.longValue();
        long day = m/dayH;
        long d1 = m%dayH;
        long hour = d1/60;
        long minute = d1%60;
        String display
            = ResourceUtil.getStringByParams("collaboration.date.display",
                    day>0 ? day: "" ,
                    day > 0 ? 1:0,
                    hour>0 ? hour : "" ,
                    hour >0 ?1:0,
                    minute >0 ? minute : "",
                    minute >0 ? 1 : 0);
        //{0}{1,choice,0#|1#\u5929}{2}{3,choice,0#|1#\u5C0F\u65F6}{4}{5,choice,0#|1#\u5206}
        return display;
    }
    
    private int  getCurrentYearWorkTime(){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int t = 0;
        try {
            t = workTimeManager.getEachDayWorkTime(year, AppContext.getCurrentUser().getLoginAccount());
        } catch (WorkTimeSetExecption e) {
        }
        return t;
    }

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public void setWapi(WorkflowApiManager wapi) {
		this.wapi = wapi;
	}

	public void setCtpCommentManager(CommentManager ctpCommentManager) {
		this.ctpCommentManager = ctpCommentManager;
	}

	public void setAffairManager(AffairManager affairManager) {
		this.affairManager = affairManager;
	}

	public void setCollaborationApi(CollaborationApi collaborationApi) {
		this.collaborationApi = collaborationApi;
	}

	public void setPermissionManager(PermissionManager permissionManager) {
		this.permissionManager = permissionManager;
	}

	public void setWorkTimeManager(WorkTimeManager workTimeManager) {
		this.workTimeManager = workTimeManager;
	}

	public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
		this.formApi4Cap4 = formApi4Cap4;
	}

	public void setBaseQiangsDao(SyncOrgDao baseQiangsDao) {
		this.baseQiangsDao = baseQiangsDao;
	}
}
